package ntd.util.frame.javacv.vlc;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sun.jna.NativeLibrary;
import com.tool.ToolSys;
import ntd.util.UtilCatch;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

public class FactoryVlc {

    //--live-caching 0设置播放器缓存为0，保证获取到的都是实时画面，第二个参数可以不加，暂时没看出啥效果
    private static String[] options = new String[]{"--live-caching 0", "--avcodec-hr=vaapi_drm"};

    private static int num = 0;

    static {
        if (ToolSys.isWindowSys()) {
            NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
        }
    }

    public static byte[] getSnapshotAboutBytes(String path) {
        BufferedImage snapshot = getSnapshot(path);
        if (ObjectUtil.isNull(snapshot)) {
            return null;
        }
        return UtilCatch.tryCatch(() -> {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(snapshot, "jpg", outputStream);
            outputStream.flush();
            return outputStream.toByteArray();
        });
    }

    public static BufferedImage getSnapshot(String path) {
        VlcContext vlcContext = VlcContext.init();
        MediaPlayer mediaPlayer = vlcContext.getHeadlessMediaPlayer();

        //开始播放视频，这里传入的是rtsp连接， 传入其他格式的链接也是可以的，网络链接、本地路径都行
        if (mediaPlayer.prepareMedia(path, options)) {
            if (mediaPlayer.start()) {
                ThreadUtil.sleep(10000);
                if (mediaPlayer.isPlaying()) {
                    // 获取截图
                    BufferedImage snapshot = mediaPlayer.getSnapshot();
                    // 释放资源
                    vlcContext.close();
                    return snapshot;
                }
            }
        }
        return null;
    }
}
